package com.tencent.qf.common.gateway.mks;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.gateway.mks.dto.MKSCommonRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * 营销中台
 */
@Slf4j
public class MKSApiUtils {

    public static String sign(MKSCommonRequest request, String appId, String appKey, long timestamp) {
        request.setApp_id(appId);
        request.setTimestamp(timestamp);
        request.setSignature(null);
        String requestBody = JSON.toJSONString(request);

        // ascii排序、拼接、md5
        TreeMap<String, Object> treeMap = JSON.parseObject(requestBody, new TypeReference<TreeMap<String, Object>>() {
        });
        StringBuilder waitEncrypted = new StringBuilder();

        Iterator iterator = treeMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            Object value = treeMap.get(key);
            if (value == null) {
                continue;
            }
            if (ObjectUtil.isBasicType(value) || value instanceof String) {
                waitEncrypted.append(key).append("=").append(URLEncoder.encode(treeMap.get(key).toString())).append("&");
            }else if(value instanceof JSONArray){
                JSONArray o = (JSONArray) value;
                int i=0;
                for(Object obj : o){
                    StringBuilder arrayStr = new StringBuilder();
                    arrayStr.append("[").append(i++).append("]");
                    waitEncrypted.append(key).append(URLEncoder.encode(arrayStr.toString())).append("=").append(URLEncoder.encode(obj.toString())).append("&");
                }
            }else {
                waitEncrypted.append(key).append("=").append(URLEncoder.encode(JSON.toJSONString(treeMap.get(key)))).append("&");
            }

        }

        waitEncrypted.append("app_key=").append(appKey);
        log.info("待验签名值；{}", waitEncrypted);
        try {
            String sign = DigestUtils.md5Hex(waitEncrypted.toString());
            log.info("签名值；{}", sign);
            request.setSignature(sign);
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getFormattedText(byte[] digest) {
        StringBuffer buffer = new StringBuffer();
        //把每一个byte，做一个与运算，0xff
        for (byte b : digest) {
            int number = b & 0xff;//加盐
            String str = Integer.toHexString(number);
            if (str.length() == 1) {
                buffer.append("0");
            }
            buffer.append(str);
        }
        //标准的md5加密后的结果
        return buffer.toString();
    }
}
